package com.young.controller;

import com.young.service.ShoppingCart;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: create by Young
 * @version: v1.0
 * @description: com.young.controller
 * @date:2019/3/23 0:28
 */
@RestController
public class AwareShoppingController implements ApplicationContextAware {
	private ApplicationContext context;
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.context = applicationContext;
	}

	//通过实现ApplicationContextAware接口从而得到context，进而从容器中取出bean
	//实现了单例controller在实例化之后，显式地从容器中获取新的购物车实例，而不是注入购物车实例
	//避免了单例只注入一次导致的多人使用同一个购物车，产生脏数据
	public ShoppingCart getInstance() {
		return (ShoppingCart)context.getBean("shoppingCart");
	}

	@GetMapping("/add2/{product}")
	public String testAddProduct(@PathVariable(value="product") String product) {
		ShoppingCart shoppingCart = getInstance();
		shoppingCart.addProduct(product);
		return shoppingCart.showProduct();
	}
}
